<template>
  <div>
    <div class="header_search_nav search_form">
      <div class="ipt_left">
        <el-form ref="queryForm" :model="queryParams" label-width="80px">
          <el-row>
            <el-col :span="5">
              <el-form-item label="区域" prop="districtId">
                <el-select
                  v-model="queryParams.districtId"
                  placeholder="请选择"
                  clearable
                  filterable
                  @change="handleQuery"
                >
                  <el-option
                    v-for="item in AreaData"
                    :key="item.districtId"
                    :label="item.districtName"
                    :value="item.districtId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="门店" prop="storeId">
                <el-select
                  v-model="queryParams.storeId"
                  placeholder="请选择"
                  filterable
                  clearable
                  @change="getList"
                >
                  <el-option
                    v-for="(item, index) in $store.state.user.stores"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="日期">
                <div class="seach-item-nav">
                  <div class="seach-item-nav-style">
                    <el-select
                      v-model="queryParams.type"
                      placeholder="请选择"
                      @change="dataTypeChange"
                    >
                      <el-option
                        v-for="item in dateOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </div>

                  <div
                    class="seach-item-nav-style"
                    v-show="
                      queryParams.type === 'Y' || queryParams.type === 'Q'
                    "
                  >
                    <el-date-picker
                      v-model="queryParams.year"
                      type="year"
                      placeholder="选择年"
                      value-format="yyyy"
                    >
                    </el-date-picker>
                  </div>

                  <div
                    class="seach-item-nav-style"
                    v-show="queryParams.type === 'M'"
                  >
                    <el-date-picker
                      v-model="queryParams.moon"
                      type="month"
                      placeholder="选择月份"
                      value-format="yyyy-MM"
                    >
                    </el-date-picker>
                  </div>

                  <div
                    class="seach-item-nav-style"
                    v-show="queryParams.type === 'Q'"
                  >
                    <el-select
                      v-model="queryParams.quarter"
                      placeholder="请选择季度"
                      clearable
                      class="w-120"
                    >
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="btn_right">
        <button class="btn1" @click="handleQuery">筛选</button>
        <button class="btn2" @click="resetQuery">重置</button>
      </div>
    </div>

    <div class="table_card">
      <!-- 上部分 title -->
      <div class="table_card_top">
        <span class="solid_left1"></span>
        <div class="table_card_title">利润费用月对比</div>
        <div class="op_right">
          <el-button
            @click="handleExport"
            :loading="exportLoading"
            class="repeat"
            v-hasPermi="['order:finance:profit:cost:moon:contrast:exl']"
            >导出</el-button
          >
        </div>
      </div>

      <div class="table_list">
        <el-table :data="ProfitList" max-height="600" style="width: 100%">
          <el-table-column
            prop="moon"
            label="月份"
            width="120"
            align="center"
            fixed="left"
          >
          </el-table-column>

          <el-table-column label="收入类目" align="center">
            <el-table-column
              v-for="items in tableHeader.keyListIn"
              :key="items.key"
              :prop="items.key"
              :label="items.label"
              width="120"
            >
            </el-table-column>
          </el-table-column>

          <el-table-column label="支出类目" align="center">
            <el-table-column
              width="120"
              v-for="items in tableHeader.keyListOut"
              :key="items.key"
              :prop="items.key"
              :label="items.label"
            >
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- echart -->
    <div class="revenue">
      <!-- 收入分析图 -->
      <barLine ref="keyInBarLine" yAxisLineTitle="同比增长率"></barLine>

      <!-- 费用分析图 -->
      <barLine ref="keyOutBarLine" yAxisLineTitle="同比增长率"></barLine>
      <div></div>
    </div>
  </div>
</template>

<script>
import { getProfitCostContrast } from "@/api/bpm/reports";
import { getProfitCostMoonExport } from "@/api/bpm/excle";
import timer from "@/components/getTime/timer";
import barLine from "@/components/charts/barLine";
import { getManagerDistrict } from "@/api/bpm/commission";

export default {
  name: "Storeadminprofitexpenses",
  components: { timer, barLine },
  data() {
    return {
      loading: false,
      exportLoading: false,
      saveLoading: false,
      value: "",
      // dialogVisible: false,
      // 查询参数
      queryParams: {
        storeId: "",
        moon: "", // 月份
        year: "",
        quarter: "", // 季度
        type: "",
        districtId: "",
      },

      AreaData: [], // 区域数据
      ProfitList: [],
      tableHeader: {},
      total: 0,
      exportLoading: false,

      tableData: [],

      expireTimeOPtion: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
        },
      },

      dateOptions: [
        {
          value: "Y",
          label: "年份",
        },
        {
          value: "M",
          label: "月份",
        },
        {
          value: "Q",
          label: "季度",
        },
      ],
      options: [
        {
          value: "1",
          label: "第一季度",
        },
        {
          value: "2",
          label: "第二季度",
        },
        {
          value: "3",
          label: "第三季度",
        },
        {
          value: "4",
          label: "第四季度",
        },
      ],
    };
  },

  mounted() {},

  created() {
    this.getList();
    this.getAreaData();
  },

  methods: {
    dataTypeChange() {
      this.queryParams.year = "";
      this.queryParams.quarter = "";
      this.queryParams.moon = "";
    },

    // 获取区域数据
    getAreaData() {
      getManagerDistrict(this.queryParams)
        .then((res) => {
          const { code, data } = res;
          if (code === 0) {
            this.AreaData = data;
          }
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    HandleClose() {
      this.resetFormData("ruleForm");
      this.$nextTick(() => {
        this.dialogVisible = false;
      });
    },

    handleExport() {
      this.$modal
        .confirm("是否确认导出报表数据?")
        .then(() => {
          this.exportLoading = true;
          return getProfitCostMoonExport(this.queryParams);
        })
        .then((response) => {
          this.$download.excel(response, "利润费用月对比");
          this.exportLoading = false;
        })
        .catch(() => {
          this.exportLoading = false;
        });
    },

    // 筛选
    handleQuery() {
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetFormData("queryForm");
      // this.queryParams.localDate = dayDataTime("obj").str;
      this.handleQuery();
    },

    // 表单重置
    resetFormData(formName) {
      console.log(this.$refs[formName]);
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
    },

    // 利润费用对比
    getList() {
      this.loading = true;

      // if (!this.queryParams.storeId) {
      //   this.$message.error("门店不能为空");
      //   return false;
      // }

      // if (!this.queryParams.moon) {
      //   this.$message.error("月份不能为空");
      //   return false;
      // }

      if (!this.queryParams.year && !this.queryParams.quarter && !this.queryParams.moon) {
        this.$message.error("日期不能为空");
        return false;
      } 
      getProfitCostContrast(this.queryParams)
        .then((res) => {
          console.log(res);
          this.loading = false;
          const { code, data } = res;
          if (code === 0) {
            this.tableHeader = data.tableHeader;
            this.ProfitList = data.data;
            let { keyListIn, keyListOut } = data.tableHeader; // 把keyListIn keyListOut从tableHeader里解构出来
            const newKeyListIn = JSON.parse(JSON.stringify(keyListIn));
            const newKeyListOut = JSON.parse(JSON.stringify(keyListOut));
            newKeyListIn.splice(keyListIn.length - 1, 1),
              newKeyListOut.splice(keyListOut.length - 1, 1),
              this.keyInChart(newKeyListIn, data.data);
            this.keyOutChart(newKeyListOut, data.data);
          }
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    keyInChart(keyListIn, data) {
      console.log("keyListIn", keyListIn);
      console.log("data1", data);
      let InxAxis = keyListIn.map((item) => {
        return item.label;
      });

      let InSeries = [];
      let Inlegend = [];

      for (let i = 0; i < data.length; i++) {
        const item = data[i]; // 取出数组里每个对象 item
        let InData = []; // 定义一个新数组
        for (let n = 0; n < keyListIn.length; n++) {
          // keyListIn数组里每个对象有个key和对应的label值
          // let item = keyListIn[i];
          if (!!item[keyListIn[n].key]) {
            // [keyListIn[n].key]  ===》 "STORE_KDBSUB"
            InData.push(parseFloat(item[keyListIn[n].key]));
            // console.log("lxy",item[keyListIn[n].key]);
          }
        }

        // console.log("哈哈哈",InData);

        if (!!item.moon && item.moon.indexOf("-") > -1) {
          Inlegend.push(item.moon);
          // console.log("aggsagsg",Inlegend);
          InSeries.push({
            name: item.moon,
            type: "bar",
            tooltip: {
              valueFormatter: function (value) {
                return value;
              },
            },
            data: InData,
          });
        } else if (item.moon === "同比增长率") {
          Inlegend.push("同比增长率");

          InSeries.push({
            name: "同比增长率",
            type: "line",
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + "%";
              },
            },
            data: InData,
          });
        }
      }
      console.log(InSeries);

      this.$nextTick(() => {
        this.$refs.keyInBarLine.init({
          xAxis: InxAxis,
          series: InSeries,
          legend: {
            data: Inlegend,
          },
        });
      });
    },

    keyOutChart(keyListOut, data) {
      console.log("keyListOut", keyListOut);
      console.log("data2", data);
      let InxAxis = keyListOut.map((item) => {
        return item.label;
      });

      let InSeries = [];
      let Inlegend = [];

      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        let InData = [];
        for (let n = 0; n < keyListOut.length; n++) {
          if (!!item[keyListOut[n].key]) {
            InData.push(parseFloat(item[keyListOut[n].key]));
          }
        }
        if (!!item.moon && item.moon.indexOf("-") > -1) {
          Inlegend.push(item.moon);
          InSeries.push({
            name: item.moon,
            type: "bar",
            tooltip: {
              valueFormatter: function (value) {
                return value;
              },
            },
            data: InData,
          });
        } else if (item.moon === "同比增长率") {
          Inlegend.push("同比增长率");

          InSeries.push({
            name: "同比增长率",
            type: "line",
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + "%";
              },
            },
            data: InData,
          });
        }
      }
      console.log(InSeries);

      this.$nextTick(() => {
        this.$refs.keyOutBarLine.init({
          xAxis: InxAxis,
          series: InSeries,
          legend: {
            data: Inlegend,
          },
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.solid_left1 {
  margin-left: 24px;
}
.goodTop {
  width: 100%;
  height: 48px;
  background: #ffffff;
  display: flex;
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.6);
  line-height: 48px;
  padding-left: 16px;
  .good_list {
    margin-right: 32px;
  }

  .good_active {
    color: #0052d9;
    border-bottom: 1px solid #0052d9;
  }
}

.w-200 {
  width: 200px;
  background: #ffffff;
  border-radius: 4px;
}

.client_name {
  font-size: 14px;
  font-weight: 400;
  color: #0052d9;
}

.give {
  height: 40px;
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  margin-top: 40px;
  line-height: 40px;
}

.el-form-item {
  margin-bottom: 20px;
}

.recharge_form {
  padding: 10px 24px;
}

.memberName {
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}
.el_row_item {
  margin-bottom: 10px;
}
.el_row_date {
  margin-top: 20px;
}
.el_row_reason {
  margin-top: 10px;
}

.el_row_date {
  .el-form-item {
    margin-bottom: 0px;
  }
}

.Order_box {
  display: flex;
  margin-left: -50px;
  .select_ipt {
    width: 130px;
    margin-right: 10px;
  }
}

.pay_ipt {
  margin-left: 50px;
}

.order_ipt {
  margin-left: -120px;
}

.timebox {
  margin-top: 10px;
}

.table_list {
  padding-bottom: 24px;
  .red {
    color: red;
  }
}

.seach-item-nav {
  display: flex;
  .seach-item-nav-style {
    margin-right: 6px;
    min-width: 120px;
  }
}
</style>
